package com.hbnu.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 需求：UDP编程接收端
 *
 * @author kittychen
 * @since 2025-10-28 16:25
 */
public class UdpReceiveDemo01 {

    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
            // 1、创建Socket
            ds = new DatagramSocket(8888);

            // 2、定义数据报包，用于接收发送端发送的数据
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

            // 3、接收数据
            ds.receive(datagramPacket);    // receive方法是阻塞式方法

            // 4、获取数据
            byte[] data = datagramPacket.getData();
            String ip = datagramPacket.getAddress().getHostAddress();
            int port = datagramPacket.getPort();
            System.out.println(ip + ":" + port + "===>" + new String(data, 0, datagramPacket.getLength()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
    }
}
